package cn.gary.oaserver.controller;


import cn.gary.oaserver.config.utils.PageUtil;
import cn.gary.oaserver.entity.TRole;
import cn.gary.oaserver.entity.vo.RoleVo;
import cn.gary.oaserver.params.PageParams;
import cn.gary.oaserver.params.Result;
import cn.gary.oaserver.service.ITRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author gary
 * @since 2024-03-15
 */
@RestController
@RequestMapping("/role")
@Api(tags = "角色控制器类")
public class TRoleController {

    @Autowired
    ITRoleService roleService;

    @GetMapping("/list")
    @ApiOperation("获取所有角色")
    public Result list() {
        return Result.success ( "角色列表", roleService.list ( ) );
    }

    @GetMapping("/getListByAdminId/{adminId}")
    @ApiOperation("根据用户Id获取所有角色")
    public Result getListByAdminId(@PathVariable("adminId") Integer adminId) {
        return Result.success ( "用户拥有的角色列表", roleService.getListByAdminId ( adminId ) );
    }

    @PostMapping("/save")
    @ApiOperation("添加角色")
    public Result save(@RequestBody TRole role) {

        String opr = "修改";
        if (role.getId ( ) == null || role.getId ( ) == 0) {
            opr = "新增";
        }
        if (roleService.saveOrUpdate ( role )) {

            return Result.success ( opr + "角色成功" );
        } else {
            return Result.error ( opr + "角色失败" );
        }
    }

    @GetMapping("/del/{id}")
    @ApiOperation("删除角色")
    public Result del(@PathVariable("id") Integer id) {
        try {
            if (roleService.removeRoleAndMenuRoleById ( id )) {
                return Result.success ( "删除角色成功" );
            } else {
                return Result.error ( "删除角色失败,该角色已绑定用户" );
            }
        } catch (Exception exception) {
            return Result.error ( "删除角色失败,该角色已绑定用户" );
        }
    }

    @GetMapping("/listTree")
    @ApiOperation("获取所有角色（三级）")
    public Result getListTree(PageParams pageParams, String queryStr) {
        System.out.println ( pageParams );
        PageUtil<RoleVo> roleAndMenuTree = roleService.getRoleAndMenuTree ( pageParams, queryStr );
        return Result.success ( "返回的树形角色", roleAndMenuTree );
    }
}
